package cn.wh.basic.controller;

import cn.wh.basic.exception.BusinessException;
import cn.wh.basic.util.AjaxResult;
import cn.wh.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 上传
     *
     * @author wh
     *
     */

    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart(value = "file",required = true) MultipartFile file){
        try {
            //获取文件的全名
            String filename = file.getOriginalFilename();
            //获取文件名的后缀
            String lastName = filename.substring(filename.lastIndexOf(".") + 1);
            //得到文件的路径
            String path = FastdfsUtil.upload(file.getBytes(), lastName);
            return AjaxResult.my().setResultObj(path);
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.my().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.my().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }
//   http://123.207.27.208/group1/M00/00/05/CgAIC2Kl-q6AU3aOAADYXI6DDUY130.jpg
    @DeleteMapping    //http://123.207.27.208/fastDfs?path=     /group1/M00/00/05/CgAIC2Kl92uAWUqRAAF877jCmbs681.jpg
    public AjaxResult delete(@RequestParam String path){
        try {
            String pathTmp = path.substring(1);//  group1/M00/00/05/CgAIC2Kl92uAWUqRAAF877jCmbs681.jpg
            String group = pathTmp.substring(0,pathTmp.indexOf("/"));//  group1
            String filename = pathTmp.substring(pathTmp.indexOf("/")+1);//  M00/00/05/CgAIC2Kl92uAWUqRAAF877jCmbs681.jpg
            FastdfsUtil.delete(group,filename);
            return AjaxResult.my();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.my().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.my().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }
}
